<template>
	<view class="container">
		<u-toast ref="uToast"></u-toast>
		<view class="content">
			<view class="item">
				<view class="labelName">商品名称</view>
				<u--input placeholder="请输入商品名称" border="surround" v-model="product.name"></u--input>
			</view>
			<u-divider text="商品描述和外观"></u-divider>
			<!-- 商品描述 -->
			<u--textarea v-model="product.description" placeholder="请输入商品描述" height="150"></u--textarea>
			<!-- 图片上传 -->
			<view>
				<imageUpload v-model="picList" maxCount="9"></imageUpload>
			</view>

			<u-divider text="分类选择/自定义标签"></u-divider>
			<!-- 分类选择/自定义标签 -->
			<view class="item">
				<view class="labelName">分类</view>
				<view class="selectTextClass" @click="selectCategory">
					{{product.productCategoryName?product.productCategoryName:"请选择分类"}}
				</view>
			</view>
			<!-- 商品的属性 新度 功能完整性 -->
			<view class="item">
				<view class="labelName">成色</view>
				<view class="columnClass">
					<view :class="product.fineness==index?'selectTextClass':'textClass'"
						v-for="(finessName,index) in finenessList" :key="index" @click="changeFineness(index)">
						{{finessName}}
					</view>
				</view>
			</view>
			<view class="item">
				<view class="labelName">功能状态</view>
				<view class="columnClass">
					<view :class="product.functionalStatus==index?'selectTextClass':'textClass'"
						v-for="(functionName,index) in functionList" :key="index"
						@click="changeFunctionalStatus(index)">{{functionName}}
					</view>
				</view>
			</view>
			<u-row customStyle="margin-bottom: 10px">
				<u-col span="5">
					<view class="item">
						<view class="labelName">数量</view>
						<u--input placeholder="请输入商品数量" border="surround" v-model="product.number"></u--input>
					</view>
				</u-col>
				<u-col span="7">
					<view class="item">
						<view class="labelName">计量单位</view>
						<u--input placeholder="请输入计量单位" border="surround" v-model="product.unit"></u--input>
					</view>
				</u-col>
			</u-row>

			<!-- 价格 原价 现价 -->
			<u-divider text="价格"></u-divider>
			<u-row customStyle="margin-bottom: 10px">
				<u-col span="6">
					<view class="item">
						<view class="labelName">原价</view>
						<u-input placeholder="请输入原价" border="surround" v-model="product.originalPrice" color="#ff0000"
							@blur="originalPriceChange">
							<u--text text="¥" slot="prefix" margin="0 3px 0 0" type="error"></u--text>
						</u-input>
					</view>
				</u-col>
				<u-col span="6">
					<view class="item">
						<view class="labelName">出售价格</view>
						<u-input placeholder="请输入出售价格" border="surround" v-model="product.price" color="#ff0000"
							@blur="priceChange">
							<u--text text="¥" slot="prefix" margin="0 3px 0 0" type="error"></u--text>
						</u-input>
					</view>
				</u-col>
			</u-row>

			<view style="display: flex;margin: 0rpx 60rpx;">
				<view style="background:#A9A9A9 ;" class="buttonView" @click="saveDraft">存 草 稿</view>
				<view style="width: 40rpx;"></view>
				<view style="background:#3C9CFF ;" class="buttonView" @click="uploadSellProduct">发 布</view>
			</view>

		</view>
	</view>
</template>

<script>
	import imageUpload from "@/components/ImageUpload/ImageUpload.vue";
	import {
		uploadSellProduct
	} from "@/api/market/product.js";
	import {
		picUrlConstruct
	} from "@/utils/picUrlConstruct.js";
	export default {
		components: {
			imageUpload
		},
		onShow: function() {
			let categoryNameList = uni.getStorageSync("categoryNameList");
			if (categoryNameList) {
				this.categoryNameList = categoryNameList;
				this.product.productCategoryId = uni.getStorageSync("productCategoryId");
				this.product.productCategoryName = categoryNameList[categoryNameList.length - 1];
				uni.removeStorageSync("categoryNameList");
				uni.removeStorageSync("productCategoryId");
			}
		},
		data() {
			return {
				product: {
					id: undefined,
					name: '',
					descripption: '',
					picList: [],
					productCategoryId: undefined,
					productCategoryName: undefined,
					number: 1,
					unit: '个',
					isContribute: 0,
					originalPrice: 0.00,
					price: 0.00,
					// 成色
					fineness: 0,
					// 功能状态
					functionalStatus: 0,
					brandId: 0
				},
				value: 'dasdas',
				categoryNameList: ["选择分类"],
				finenessList: ["全新", "几乎全新", "轻微使用痕迹", "明显使用痕迹", "外观破损"],
				functionList: ["功能完好无维修", "维修过，可正常使用", "有小问题，不影响使用", "无法正常使用"],
				picList: [],
			}
		},
		onLoad(e) {
			if (e.productVo) {
				// 路由中携带了产品信息，说明是要修改产品信息
				this.product = JSON.parse(decodeURIComponent(e.productVo));
				for (var i = 0; i < this.product.picList.length; i++) {
					this.picList.push(this.product.picList[i].address);
				}
				console.log("this.product:" + JSON.stringify(this.product));
				console.log("this.picList:" + JSON.stringify(this.picList));
			}
		},
		methods: {
			getCategoryLayerName() {
				let str = '';
				// for (let i = 0; i < this.categoryNameList.length - 1; i++) {
				// 	str += this.categoryNameList[i] + '/';
				// }
				return str + this.categoryNameList[this.categoryNameList.length - 1];
			},
			/**
			 * 价格校验
			 * @param {Object} price 价格
			 */
			priceVerify(price) {
				if (isNaN(price)) {
					this.$refs.uToast.show({
						type: 'error',
						message: "输入的价格不是数字，请重新输入"
					})
					return false;
				}
				if (price < 0) {

					this.$refs.uToast.show({
						type: 'error',
						message: "输入的价格不能为负数，请重新输入"
					})
					return false;
				}
				if (price.toString().indexOf('.') !== -1 && price.toString().split('.')[1].length > 2) {
					this.$refs.uToast.show({
						type: 'error',
						message: "输入的价格小数点后最多只有两位数字，请重新输入"
					})
					return false;
				}
				return true;
			},
			originalPriceChange() {
				let haha = this.priceVerify(this.product.originalPrice);
				if (haha === false) {
					console.log("haha:" + haha);
					this.product.originalPrice = 0.00;
					console.log("this.product" + JSON.stringify(this.product));
				}
			},
			priceChange() {
				if (this.priceVerify(this.product.price) === false) {
					this.product.price = 0.00;
				}
			},
			/**
			 * 修改成色
			 * @param {Object} index
			 */
			changeFineness(index) {
				this.product.fineness = index;
			},
			/**
			 * 修改功能状态
			 * @param {Object} index
			 */
			changeFunctionalStatus(index) {
				this.product.functionalStatus = index;
			},
			/**
			 * 上传闲置商品
			 */
			uploadSellProduct() {
				console.log("上传闲置商品picList:" + JSON.stringify(this.picList));
				if (this.product.productCategoryId) {
					if (this.picList.length == 0) {
						this.$refs.uToast.show({
							type: 'error',
							message: "商品图片没有上传成功"
						})
					} else {
						this.setPicAspectRatio().then(() => {
							console.log("即将上传的商品：" + JSON.stringify(this.product));
							this.product.status = 0;
							uploadSellProduct(this.product).then(res => {
								if (!this.product.id) {
									this.$refs.uToast.show({
										type: 'success',
										message: "您的商品已经发布到平台"
									})
								} else {
									this.$refs.uToast.show({
										type: 'success',
										message: "您的商品修改并发布成功"
									})
								}
								let _that = this;
								setTimeout(() => {
									// 获取上一页
									let pages = getCurrentPages();
									// let prevPage = pages[pages.length - 2];
									// 调用上一页的返回方法
									// if (_that.Constant.softType == 1) {
									// 	prevPage.$vm.back();
									// }
									uni.navigateBack();
								}, 500)
							}).catch(error => {
								console.log("error:" + JSON.stringify(error));
								this.$refs.uToast.show({
									type: 'error',
									message: error.msg
								})
							});
						});

					}
				} else {
					this.$refs.uToast.show({
						type: 'error',
						message: "请选择分类"
					})
				}
			},
			/**
			 * 保存商品草稿
			 */
			saveDraft() {
				this.setPicAspectRatio().then(() => {
					// console.log("即将上传的商品：" + JSON.stringify(this.product));
					this.product.status = 3;
					uploadSellProduct(this.product).then(res => {
						this.$refs.uToast.show({
							type: 'success',
							message: "您的草稿保存成功"
						})
						let _that = this;
						setTimeout(() => {
							// 获取上一页
							let pages = getCurrentPages();
							let prevPage = pages[pages.length - 2];
							// 调用上一页的返回方法
							if (_that.Constant.softType == 1) {
								prevPage.$vm.back();
							}
							uni.navigateBack();
						}, 500)
					}).catch(error => {
						// console.log("error:" + JSON.stringify(error));
						this.$refs.uToast.show({
							type: 'error',
							message: "草稿保存失败"
						})
					});
				});

			},

			/**
			 * 设置图片的宽高比
			 */
			setPicAspectRatio() {
				return new Promise((resolve, reject) => {
					this.product.picList = [];
					let promises = [];
					for (let i = 0; i < this.picList.length; i++) {
						let picUrl = picUrlConstruct(this.picList[i]);
						promises.push(this.getAspectRatio(picUrl).then((res) => {
							let pic = {
								address: this.picList[i],
								aspectRatio: res
							}
							this.product.picList.push(pic);
							console.log("当前图片高宽比设置完成");
						}))
					}
					Promise.all(promises).then(() => {
						console.log("所有图片高宽比设置完成，this.product.picList:" + JSON.stringify(this.product
							.picList));
						resolve();
					})
				})
			},
			/**
			 * 获取单个图片的高宽比

			 * @param {Object} url
			 */
			getAspectRatio(url) {
				return new Promise((resolve, reject) => {
					uni.getImageInfo({
						src: url,
						success: function(res) {
							let aspectRatio = res.height / res.width;
							resolve(aspectRatio);
						}
					});
				})
			},

			/**
			 * 选择分类
			 */
			selectCategory() {
				uni.navigateTo({
					url: "/pages/sellMyProduct/selectCategory"
				})
			}
		}
	}
</script>

<style lang="scss">
	.container {
		background: #F6F6F6;
		min-height: 100vh;
		padding: 20rpx;
		font-family: sans-serif;

		.content {
			background: #ffffff;
			padding: 20rpx;


			.item {
				display: flex;
				align-items: center;
				height: 50px;
				margin-bottom: 5px;

				.labelName {
					width: 70px;
					margin-right: 10px;
				}

				.textClass {
					display: inline;
					background: #F7F7F7;
					padding: 15rpx;
					margin-right: 15px;
					border-radius: 5px;
				}

				.selectTextClass {
					display: inline;
					background: #2B92FF;
					padding: 15rpx;
					margin-right: 15px;
					border-radius: 5px;
					color: #ffffff;
					// font-weight: bold;
				}

				.columnClass {
					// height: 50px;
					display: flex;
					align-items: center;

					width: calc(100% - 70px);
					overflow-x: auto;
					// // 让内容只有一行
					white-space: nowrap;
				}

				.columnClass::-webkit-scrollbar {
					background-color: transparent;
					/* 设置滚动条背景颜色 */
					// width: 0px;
					height: 0px;
				}

			}

			.buttonView {
				padding: 20rpx;
				flex: 1;
				text-align: center;
				border-radius: 10rpx;
				color: #ffffff;
				font-weight: bold;
			}

		}
	}
</style>